﻿using System;
using System.Threading.Tasks;

namespace Codeflows.Results
{
    public class PendingResult : Result
    {
        public PendingResult(Task<Result> pendingTask)
        {
            if (pendingTask == null) throw new ArgumentNullException("pendingTask");

            // Thunk the callsite to return a suspended result when user exception goes unhandled.
            PendingTask = pendingTask.ContinueWith(t=>
                                                       {                                                           
                                                           var result = t.Exception == null
                                                                            ? t.Result
                                                                            : new SuspendedResult(t.Exception);
                                                           DiagnosticsUtility.Verbose("Pending operaation completed with a {0}.", result);
                                                           return result;
                                                       }, 
                TaskContinuationOptions.ExecuteSynchronously);
        }

        public Task<Result> PendingTask { get; private set; }

        internal void ContinueWith(Func<Task<Result>, Result> continuationAction)
        {
            PendingTask = PendingTask.ContinueWith(continuationAction);
        }
    }
}
